/* Copyright (C) 2011 Riccardo Marson

   This file is part of OpenPool, an open-source game of pool. 

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   RICCARDO MARSON BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
   AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  See Readme.rtf for further information.
  
*/

#include "Constants.h"

#include "application.h"
#include <string.h>
#include <stdio.h>

//---------------------------------------
// CConfigOptions
//---------------------------------------

CConfigOptions::CConfigOptions()
{
	windowWidth = 1024;
	windowHeight = 768;
	castShadows = true;
	playMusic = false;
	playSoundEffects = true;
	gravity = 18.0;
	airDensity = 0.2;
	frictionCoefficient = 0.7;
	simTimeStep = 0.025;
	physicsDebugModeOn = false;
	logFileName = "log.txt";
	logDebugModeActive = false;

}

CConfigOptions::~CConfigOptions()
{

}


void CConfigOptions::saveConfigOptions()
{


}

//---------------------------------------
// CLevelLoader
//---------------------------------------

void CLevelLoader::NewObject(CScriptDictionary* objTable)
{

	objTable->AddRef();

	// Enums are registered script-side as INT64
	int64_t type_buffer;

	eObjectType obj_type;

	objTable->Get("type", &type_buffer, asTYPEID_INT64);

	obj_type = static_cast<eObjectType>(type_buffer);

	switch (obj_type)
	{
	case TYPE_MOVABLE:
		AddObject(objTable, TYPE_MOVABLE);
		break;
	case TYPE_STATIC:
		AddObject(objTable, TYPE_STATIC);
		break;
	case TYPE_PROP:
		AddObject(objTable, TYPE_PROP);
		break;
	case TYPE_LIGHT:
		AddLight(objTable);
		break;
	case TYPE_CAMERA:
		AddCamera(objTable);
		break;
	default:
		break;
	}

	objTable->Release();
}

void CLevelLoader::AddObject(CScriptDictionary* objTable, eObjectType type)
{
	// buffers by data type
	bool bool_buf;
	double num_buf;
	CVector3 vec_buf;
	CMaterial mat_buf;
	string str_buf;
	// Enums are registered script-side as INT64
	int64_t id_buffer;
	int64_t cs_buffer;

	eObjectID obj_id;
	eCollisionShape cs_id;

	ObjectPtr obj = ObjectPtr(new CObject());

	// Not all properties are necessarily set for each incoming object!

	if ( objTable->Get("id", &id_buffer, asTYPEID_INT64) )
	{
		obj_id = static_cast<eObjectID>(id_buffer);

		obj->SetObjectType(type);
		obj->SetObjectID(obj_id);
	}

	if ( objTable->Get("name", &str_buf, mParent->scriptManager->GetASTypeID("string")) )
	{
		obj->SetName(str_buf);
	}

	if ( objTable->Get("mass", &num_buf, asTYPEID_DOUBLE) )
	{
		obj->SetMass(num_buf);
	}

	if ( objTable->Get("pos", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3") ) )
	{
		obj->SetPosition(vec_buf);
	}

	if ( objTable->Get("vel", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		obj->SetVelocity(vec_buf);
	}

	if ( objTable->Get("rotaxis", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		obj->SetRotationAxis(vec_buf);
	}

	if ( objTable->Get("rotangle", &num_buf, asTYPEID_DOUBLE) )
	{
		obj->SetRotationAngle(num_buf);
	}

	if ( objTable->Get("active", &bool_buf, asTYPEID_BOOL) )
	{
		obj->SetActive(bool_buf);
	}

	if ( objTable->Get("falling", &bool_buf, asTYPEID_BOOL) )
	{
		obj->SetFalling(bool_buf);
	}

	if ( objTable->Get("visible", &bool_buf, asTYPEID_BOOL) )
	{
		obj->SetVisible(bool_buf);
	}

	if ( objTable->Get("shape", &cs_buffer, asTYPEID_INT64) )
	{
		cs_id = static_cast<eCollisionShape>(cs_buffer);

		AddCollisionShape(obj, cs_id, objTable);
	}

	if ( objTable->Get("material", &mat_buf, mParent->scriptManager->GetASTypeID("Material")) )
	{
		CMeshInfo info;
		info.defaultMaterial = (mat_buf);

		if ( objTable->Get("modelname", &str_buf, mParent->scriptManager->GetASTypeID("string")) )
		{
			info.modelName = str_buf;
			info.hasModel = true;
		}

		obj->SetMeshInfo(info);
	}
	else if ( objTable->Get("modelname", &str_buf, mParent->scriptManager->GetASTypeID("string")) )
	{
		CMeshInfo info;

		info.modelName = str_buf;

		info.hasModel = true;

		obj->SetMeshInfo(info);
	}

	if (obj->GetObjectType() != TYPE_PROP)
		mParent->gameLogic->AttachObject(obj);

	GLObjectPtr globj = GLObjectPtr( new COGLObject() );

	globj->Type() = obj->GetObjectType();
	globj->Id() = obj->GetObjectID();
	globj->Name() = obj->GetName();
	globj->ModelFileName() = obj->GetMeshInfo().modelName;
	globj->HasModel() = obj->GetMeshInfo().hasModel;
	globj->IsVisible() = obj->IsVisible();
	globj->Material() = obj->GetMeshInfo().defaultMaterial;

	globj->Position().SetComponents( -obj->GetPosition().x(),
			obj->GetPosition().z(),
			obj->GetPosition().y() );

	globj->RotationAxis().SetComponents( -obj->GetRotationAxis().x(),
			obj->GetRotationAxis().z(),
			obj->GetRotationAxis().y() );

	globj->RotationAngle() = obj->GetRotationAngle();

	CVector3 head(1.0, 0.0, 0.0);
	globj->Heading() = CVector3::RotateZ( obj->GetRotationAngle() * mathc::DEG2RAD, head );

	globj->Heading() = CVector3( -globj->Heading().x(),
			globj->Heading().z(),
			globj->Heading().y() );

	mParent->renderWindow->addObject(globj);

}

void CLevelLoader::AddLight(CScriptDictionary* objTable)
{
	// buffers by data type
	string str_buf;
	CVector3 vec_buf;
	CMaterial mat_buf;
	// Enums are registered script-side as INT64
	int64_t id_buffer;
	eLightType light_id;

	GLLightPtr light;

	if ( objTable->Get("id", &id_buffer, asTYPEID_INT64) )
	{
		light_id = static_cast<eLightType>(id_buffer);
	}
	else
		return;

	switch(light_id)
	{
	case LIGHT_POINT:
	{
		light = GLLightPtr(new CPointLight());
		break;
	}
	case LIGHT_SPOT:
		// placeholder
		break;
	}

	if ( objTable->Get("name", &str_buf,  mParent->scriptManager->GetASTypeID("string")) )
	{
		light->SetName(str_buf);
	}

	if ( objTable->Get("pos", &vec_buf,  mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		CVector3 glvec( -vec_buf.x(), vec_buf.z(), vec_buf.y() );
		light->SetPosition(glvec);
	}

	if ( objTable->Get("vel", &vec_buf,  mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		//TODO add velocity to light
		//light->setVelocity(vec_buf);
	}

	if ( objTable->Get("material", &mat_buf, mParent->scriptManager->GetASTypeID("Material")) )
	{
		light->SetDiffuseColor( mat_buf.diffuse[0], mat_buf.diffuse[1],
				mat_buf.diffuse[2], mat_buf.diffuse[3] );
		light->SetAmbientColor( mat_buf.ambient[0], mat_buf.ambient[1],
				mat_buf.ambient[2], mat_buf.ambient[3] );
		light->SetSpecularColor( mat_buf.specular[0], mat_buf.specular[1],
				mat_buf.specular[2], mat_buf.specular[3] );
	}

	mParent->renderWindow->addLight(light);
}

void CLevelLoader::AddCamera(CScriptDictionary* objTable)
{
	// buffers by data type
	string str_buf;
	double num_buf;
	CVector3 vec_buf;

	GLCameraPtr camera(new CBasicCamera());

	if ( objTable->Get("name", &str_buf,  mParent->scriptManager->GetASTypeID("string")) )
	{
		camera->SetName(str_buf);
	}

	if ( objTable->Get("pos", &vec_buf,  mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		CVector3 glvec( -vec_buf.x(), vec_buf.z(), vec_buf.y() );
		camera->SetPosition(glvec);
	}

	if ( objTable->Get("vel", &vec_buf,  mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		//TODO add velocity to camera
		//camera->setVelocity(vec_buf);
	}

	if ( objTable->Get("look", &vec_buf,  mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		CVector3 glvec( -vec_buf.x(), vec_buf.z(), vec_buf.y() );
		camera->SetLookAt(glvec);
	}

	if ( objTable->Get("up", &vec_buf,  mParent->scriptManager->GetASTypeID("Vector3")) )
	{
		CVector3 glvec( -vec_buf.x(), vec_buf.z(), vec_buf.y() );
		camera->SetUpVector(glvec);
	}

	if ( objTable->Get("near", &num_buf, asTYPEID_DOUBLE) )
	{
		camera->SetClipDistanceNear(num_buf);
	}

	if ( objTable->Get("far", &num_buf, asTYPEID_DOUBLE) )
	{
		camera->SetClipDistanceFar(num_buf);
	}

	mParent->renderWindow->initCamera(camera);

}

void CLevelLoader::AddCollisionShape(ObjectPtr obj, eCollisionShape csID, CScriptDictionary* objTable)
{
	// object buffers by type
	double num_buf;
	CVector3 vec_buf;

	switch (csID)
	{
	case CS_SPHERE:
	{
		CollisionShapePtr cs = CollisionShapePtr(new CSphere());

		if ( objTable->Get("radius", &num_buf, asTYPEID_DOUBLE) )
		{
			CSphere* sph = dynamic_cast<CSphere*>(cs.get());

			sph->SetRadius(num_buf);

			obj->SetCollisionShape(cs);

		}
	}
		break;
	case CS_PLANE:
	{
		CollisionShapePtr cs = CollisionShapePtr(new CPlane());

		if ( objTable->Get("normal", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
		{
			CPlane* pla = dynamic_cast<CPlane*>(cs.get());

			pla->SetNormal(vec_buf);

			obj->SetCollisionShape(cs);

		}
	}
		break;
	case CS_SOCKET:
	{
		CollisionShapePtr cs = CollisionShapePtr(new CSocket());

		if ( objTable->Get("radius", &num_buf, asTYPEID_DOUBLE) )
		{
			CSocket* sph = dynamic_cast<CSocket*>(cs.get());

			sph->SetRadius(num_buf);

			obj->SetCollisionShape(cs);
		}
	}
	break;
	case CS_BOX:
	{
		CollisionShapePtr cs = CollisionShapePtr(new CBox());

		CBox* box = dynamic_cast<CBox*>(cs.get());

		// not all the box planes need to be defined (open boxes are allowed)

		if ( objTable->Get("offset1", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
		{
			CVector3 normal;

			objTable->Get("normal1", &normal, mParent->scriptManager->GetASTypeID("Vector3"));

			box->AddPlane(vec_buf, normal);
		}

		if ( objTable->Get("offset2", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
		{
			CVector3 normal;

			objTable->Get("normal2", &normal, mParent->scriptManager->GetASTypeID("Vector3"));

			box->AddPlane(vec_buf, normal);
		}

		if ( objTable->Get("offset3", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
		{
			CVector3 normal;

			objTable->Get("normal3", &normal, mParent->scriptManager->GetASTypeID("Vector3"));

			box->AddPlane(vec_buf, normal);
		}

		if ( objTable->Get("offset4", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
		{
			CVector3 normal;

			objTable->Get("normal4", &normal, mParent->scriptManager->GetASTypeID("Vector3"));

			box->AddPlane(vec_buf, normal);
		}

		if ( objTable->Get("offset5", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
		{
			CVector3 normal;

			objTable->Get("normal5", &normal, mParent->scriptManager->GetASTypeID("Vector3"));

			box->AddPlane(vec_buf, normal);
		}

		if ( objTable->Get("offset6", &vec_buf, mParent->scriptManager->GetASTypeID("Vector3")) )
		{
			CVector3 normal;

			objTable->Get("normal6", &normal, mParent->scriptManager->GetASTypeID("Vector3"));

			box->AddPlane(vec_buf, normal);
		}

		obj->SetCollisionShape(cs);

	}
		break;
	default:
		break;
	}

}

